#!/bin/bash
{% set KUBE_APISERVER_ADDR, KUBE_APISERVER_PORT = ansible_default_ipv4.address, 6443 %}
{% if inventory_hostname in groups['master'] %}
  {% set KUBE_APISERVER_ADDR, KUBE_APISERVER_PORT = ansible_default_ipv4.address, 6443 %}
{% else %}
  {% if ha.type | default('none') == "none" %}
    {% set KUBE_APISERVER_ADDR, KUBE_APISERVER_PORT = hostvars[groups['master'][0]].inventory_hostname, 6443 %}
  {% else %}
    {% if ha.type | default('none') == "slb" %}
      {% set KUBE_APISERVER_ADDR, KUBE_APISERVER_PORT = ha.vip, 8443 %}
    {% else %}
      {% set KUBE_APISERVER_ADDR, KUBE_APISERVER_PORT = ha.vip, 6443 %}
    {% endif %}
  {% endif %}
{% endif %}

retry=0
for ((i = 1; i <= 5; i++)); do
  nodeStats=$(curl -s --cacert /etc/kubernetes/pki/ca.crt --cert /etc/kubernetes/pki/kubelet.crt --key /etc/kubernetes/pki/kubelet.key https://{{ KUBE_APISERVER_ADDR }}:{{ KUBE_APISERVER_PORT }}/api/v1/nodes/{{ ansible_hostname | lower }} | jq -r '.status.conditions[] | select(.type=="Ready")| .status')
  if [ ${nodeStats} == "True" ]; then
    break
  fi
  echo "Check node status is not 'True', restart kubelet services, retry: ${i}."
  systemctl restart kubelet.service
  sleep 10
done
